from django.conf import settings
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.forms import AuthenticationForm
from django.http import HttpResponseRedirect as redirect
from django.contrib.auth import authenticate
from StartGroup.models import Group
from groupevents.models import Events, Event_Comment, Event_Rsvp
from contifyuser.models import Member
from groupevents.forms import CreateEventForm, PostEventCommentForm
import StartGroup.Constants
import Constants
import connectpeople.Constants
import datetime
import utils.signals
from django.contrib.auth.models import User
from groupMembers.models import Member_Group
import simplejson
from django.http import HttpResponse
from django.core.paginator import Paginator

# render form for creating a new event
def CreateNewEventForm(request):
    group_web_addr = request.session[connectpeople.Constants.session_group_web_address]
            
    # Create New Event form initialization
    create_event_form = CreateEventForm()
    return render_to_response(Constants.groupevents + Constants.create_new_event_template,
                              {Constants.create_event_form_constant: create_event_form,
                               'event': None},
                              context_instance = RequestContext(request))
    

# render new event confirmation
def CreateNewEvent(request):
    if connectpeople.Constants.session_group_web_address in request.session:
        group_web_addr = request.session[connectpeople.Constants.session_group_web_address]
        group = getGroupInfo(group_web_addr)
        
        if request.method == 'POST':
            # Get user ids of all users associated with the group
            grp_mem_usrid = getGroupMembersUserIds(group)
            # Get email ids of these users
            recipient_list = User.objects.filter(username__in=grp_mem_usrid).values_list('email', flat=True)
            # Compose subject for the email
            subj = group.group_name + " - New Event Created"
            if 'event_id' in request.session:
                # Get info values if exist
                event_info = Events.objects.get(id=request.session['event_id'])
                event_info.event_name = request.POST.__getitem__('event_name')
                event_info.event_place = request.POST.__getitem__('event_place')
                event_info.event_date = datetime.date(int(request.POST.__getitem__('event_date_year')), int(request.POST.__getitem__('event_date_month')), int(request.POST.__getitem__('event_date_day')))
                event_info.event_desc = request.POST.__getitem__('event_desc')
                event_info.save()
                # Send the confirmation email to members of the group
                utils.signals.send_mail.send(
                   sender=Events, email=recipient_list, model=event_info, subject=subj, template="email/createEventEmail.html")
            else:
                # Create New Event form initialization
                create_event_form = CreateEventForm(data=request.POST)
                if create_event_form.is_valid():
                    create_event_form.save(group)
                    # Send the confirmation email to members of the group
                    utils.signals.send_mail.send(
                   sender=Events, email=recipient_list, model=request.POST, subject=subj, template="email/createEventEmail.html")
    
    return render_to_response(StartGroup.Constants.start_group + StartGroup.Constants.group_registered_template,
                              {Constants.group_info_constant: group},
                              context_instance = RequestContext(request))
    
# render group event view
def event_view(request, id):
    # Get events object
    event = Events.objects.get(id=id)
    
    userid = request.session[connectpeople.Constants.session_userid]
    user = getUserInfo(userid)
    member = getMemberInfo(user)
    group_web_addr = request.session[connectpeople.Constants.session_group_web_address]
    group = getGroupInfo(group_web_addr)
    userRsvpRow = getUserRsvp(event, userid)

    # Save/Delete comment if posted
    if request.method == 'POST':
        #  Get the rsvp value
        try:
            rsvp = request.POST.__getitem__('rsvp')
        except:
            # If attribute not defined then request has come
            # to add new comment
            rsvp = None
        
        if rsvp:
            save_rsvp(event,userid,rsvp)
            # Set response to success
            response = simplejson.dumps({'success':'success'})
        else:
            # Get the comment id to be deleted
            try:
                commid = request.POST.__getitem__('commid')
            except:
                # If attribute not defined then request has come
                # to add new comment
                commid = None
                
            if commid:
                # Delete the comment from database
                Event_Comment.objects.get(id=commid).delete()
                # Set response to success
                response = simplejson.dumps({'success':'success'})
            else:
                # Create New Event form initialization
                post_event_comment_form = PostEventCommentForm(data=request.POST)
                if post_event_comment_form.is_valid():           
    
                    # Save the form
                    post_event_comment_form.save(event, member.first_name, member.photo)
                    # Update last updated values
                    #updateEventLastUpdate(event, member.first_name)
                    
                    ## Get user ids of all users associated with the group
                    #grp_mem_usrid = getGroupMembersUserIds(group)
                    ## Get email ids of these users
                    #recipient_list = User.objects.filter(username__in=grp_mem_usrid).values_list('email', flat=True)
                    ## Compose subject for the email
                    #subj = discussion.topic + " discussion - New Comment Posted"
                    ## Send Email alerts
                    #utils.signals.send_mail.send(
                    #   sender=Discussion, email=recipient_list, model=member.first_name, subject=subj, template="email/newCommentEmail.html")
                    
                    # Recent comment info
                    rec_post_dt = datetime.datetime.now().strftime('%Y, %b, %d')
                    rec_comment = request.POST
                    recentPost = {'rpd': rec_post_dt, 'rc': rec_comment}
                    # Set response to same input comment value
                    response = simplejson.dumps(recentPost)
            

    if request.is_ajax():
        return HttpResponse(response,
        content_type="application/javascript")
  
    # Post New Comment form initialization
    post_event_comment_form = PostEventCommentForm()
    
    comments = getComments(event)
    comments_list = geCommentsList(comments)
    paginator = Paginator(comments_list, 10)

    
    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        pages = paginator.page(page)
    except (EmptyPage, InvalidPage):
        pages = paginator.page(paginator.num_pages)

    
    return render_to_response("groupevents/event_view.html",
                              {'event': event, 'post_event_comment_form': post_event_comment_form,
                               'pages': pages, 'curr_member': member, 'curr_date': datetime.date.today(),
                               'rsvp_row': userRsvpRow},
                              context_instance = RequestContext(request))
    
# Render Event form to edit
def edit_event(request, id):
    # Save event id to session
    request.session['event_id'] = id
    
    # Get Events object
    event = Events.objects.get(id=id)
    
    # Create New Event form initialization
    create_event_form = CreateEventForm()
    return render_to_response(Constants.groupevents + Constants.create_new_event_template,
                              {Constants.create_event_form_constant: create_event_form,
                               'event': event},
                              context_instance = RequestContext(request))

# Save rsvp
def save_rsvp(event_info, userid, rsvp):
    # Get rsvp if user already rsvped to the event
    rsvp_row = getUserRsvp(event_info, userid)        
    if rsvp_row:
        rsvp_row.rsvp_val = rsvp
        rsvp_row.save()
    else:
        eventRsvp = Event_Rsvp(event=event_info, user_id = userid, rsvp_val = rsvp, response_date = datetime.datetime.now())
        eventRsvp.save()
    
# Get User's RSVP value for the event
def getUserRsvp(event_info, userid):
    try:
        rsvp_row = Event_Rsvp.objects.get(event=event_info, user_id=userid)
    except:
        rsvp_row = None
    return rsvp_row

# Helper function to obtain Group related to a group_web_address
def getGroupInfo(group_web_addr):
    return Group.objects.get(group_web_address= group_web_addr)
    
# Get All the members associated with the group
def getGroupMembersUserIds(group):
    return Member_Group.objects.filter(group = group).values_list('user_id', flat=True)

# Get the list of email confirmation recipients
def getRecipientList(user_list):
    recipient_list = []
    if user_list is not None:
        for each in user_list:
            recipient_list.append(each.email)
    
    return recipient_list

# Helper function to obtain Comments related to the Discussion
def getComments(event_info):
    return Event_Comment.objects.filter(event = event_info).order_by('-post_date')
    
# Helper function to obtain user info from User model
def getUserInfo(userid):
    return User.objects.get(username=userid)
    
# Helper function to obtain member info from Member model
def getMemberInfo(user_info):
    return Member.objects.get(user=user_info)

# Helper function to obtain Comments in a list format
def geCommentsList(event_comments):
    num_posts = 0
    event_comments_list = []
    if event_comments is not None:
        for each in event_comments:
            event_comments_list.append(each)
    
    return event_comments_list
    